<?php

namespace app\admin\controller\retail;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use think\Db;
use think\Exception;

/**
 * 合伙人列表
 *
 * @icon fa fa-user
 */
class Partner extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id';

    protected $areaModel = null;
    protected $usermodel = null;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {   
        $groupdata = [1=>'共创合伙人',2=>'城市合伙人',3=>'区县合伙人',4=>'乡镇合伙人'];
        parent::_initialize();
        $this->model     =  new \app\admin\model\retail\Partner;
        $this->usermodel =  new \app\admin\model\shopro\user\User;
        $this->areaModel =  model('Cnarea2019');
        $this->view->assign('groupdata', $groupdata);
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();

            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $conf_db = db('retail_partner_config')->where('type',$params['level'])->find();
                $user = db('user')->field('nickname')->where('id',$params['uid'])->find();
                if(!isset($user['nickname'])){
                    $this->error('用户不存在');
                }
                $partner = db('retail_partner')->field('uid')->where('uid',$params['uid'])->find();
                if(isset($partner['uid'])){
                    $this->error('用户已经是合伙人');
                }
                $params['user_name'] = $user['nickname'];
                $params['ys_conf'] = empty($params['ys_conf'])? $conf_db['ys_conf'] : $params['ys_conf'];
                $params['jd_conf'] = empty($params['jd_conf'])? $conf_db['jd_conf'] : $params['jd_conf'];
                $params['cs_conf'] = empty($params['cs_conf'])? $conf_db['cs_conf'] : $params['cs_conf'];
                /**过滤区域信息数据 */
                $params = $this->doarea($params);
                /**发送奖励间推和直接推荐等等 */
                $result = $this->doAddreword($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                $this->success();
            }
            $this->error();
        }

        return $this->view->fetch();
    }

    /**
     * 发送奖励
     */
    public function doAddreword($params){

        /**配置比例信息*/
        $par_conf = db('retail_partner_config')->field('join_num,tj_conf,jt_conf')->where('type',$params['level'])->find();
        $has_ppid = 0;
        $has_pid  = 0;
        /**1发送直接上级的推荐奖励 */
        $retail_user = db('retail_user')->field('uid,pid')->where('uid',$params['uid'])->find();
        $partner_info = $this->model->field('id,uid')->where('uid',$retail_user['pid'])->find();
        if(!isset($retail_user)){
            $this->error('用户不是分销的用户');
        }
        $diyiji_uid = $retail_user['pid']; //上级uid
        if($diyiji_uid != '0') $has_pid = 1;
        if($has_pid){
            $user1 = db('user')->field('money')->where('id',$diyiji_uid)->find();
            $reword_money = $par_conf['join_num'] * $par_conf['tj_conf']; //上级奖励的金钱
            $after_money  = $user1['money'] + $reword_money;  //之后的用户余额 
        }
        /** 获取上上级的uid发放间推积分*/
        $retail_user2 = db('retail_user')->field('uid,pid')->where('uid',$diyiji_uid)->find();
        $partner_info2 = $this->model->field('id,uid')->where('uid',$retail_user2['pid'])->find();
        if(isset($retail_user2['pid'])){
             if($retail_user2['pid'] !=0)$has_ppid = 1; //判断是否有上上级
        }
        if($has_ppid){
            $user2 = db('user')->field('score')->where('id',$retail_user2['pid'])->find();
            $reword_score = $par_conf['join_num'] * $par_conf['jt_conf']; //上上级奖励的积分
            $after_score  = $user2['score'] + $reword_score;  //之后的用户积分
        }
        
        Db::startTrans();
        try {
            $result = $this->model->insert($params);
            /**更新上级推荐奖励*/
            if($has_pid){
                if(isset($partner_info)){
                    $this->model->where('uid',$diyiji_uid)->update(['tj_income'=>$reword_money]);
                }
                db('user')->where('id',$diyiji_uid)->update(['money'=>$after_money]);
                /**写入钱包日志 */
                Db::name('shopro_user_wallet_log')->insert([
                    'user_id' => $diyiji_uid,
                    'wallet' => $reword_money,
                    'type' => 'partner_reward'.$params['level'],
                    'wallet_type' => 'money',
                    'item_id' => 0,
                    'oper_type' => 'system',
                    'oper_id' => 0,
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
                $current_wallet_log_id = Db::name('shopro_user_wallet_log')->getLastInsID();
                // 钱包变动通知
                $currentWalletLog = \addons\shopro\model\UserWalletLog::where('id', $current_wallet_log_id)->find();
                $user = $this->usermodel->get($diyiji_uid);
                $user->notify(
                    new \addons\shopro\notifications\Wallet([
                        'walletLog' => $currentWalletLog,
                        'event' => $currentWalletLog['wallet_type'] == 'money' ? 'wallet_change' : 'score_change'
                    ])
                );

                //写入日志
                MoneyLog::create(['user_id' => $diyiji_uid, 'money' => $reword_money, 'before' => $user1['money'] , 'after' => $after_money, 'memo' => '下级成员升级为合伙人']);
            }

            /**更新上上级推荐积分*/
            if($has_ppid){
                if(isset($partner_info2['uid'])){
                    $this->model->where('uid',$retail_user2['pid'])->update(['jifen'=>$reword_score]);
                }
                db('user')->where('id',$retail_user2['pid'])->update(['score'=>$after_score]);
                /**写入钱包日志 */
                Db::name('shopro_user_wallet_log')->insert([
                    'user_id' => $retail_user2['pid'],
                    'wallet' => $reword_score,
                    'type' => 'partner_admin_reword'.$params['level'],
                    'wallet_type' => 'score',
                    'item_id' => 0,
                    'oper_type' => 'system',
                    'oper_id' => 0,
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
                $current_wallet_log_id = Db::name('shopro_user_wallet_log')->getLastInsID();
                // 钱包变动通知
                $currentWalletLog = \addons\shopro\model\UserWalletLog::where('id', $current_wallet_log_id)->find();
                $user = $this->usermodel->get($retail_user2['pid']);
                $user->notify(
                    new \addons\shopro\notifications\Wallet([
                        'walletLog' => $currentWalletLog,
                        'event' => $currentWalletLog['wallet_type'] == 'money' ? 'wallet_change' : 'score_change'
                    ])
                );
                ScoreLog::create(['user_id' => $retail_user2['pid'], 'score' => $reword_score, 'before' => $user2['score'], 'after' => $after_score, 'memo' => '下下级升级为合伙人']);
            }
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        return $result;
    }


    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public function money($money, $user_id, $memo)
    {
        $user = self::get($user_id);
        if ($user && $money != 0) {
            $before = $user->money;
            $after = $user->money + $money;
            //更新会员信息
            $user->save(['money' => $after]);
            //写入日志
            MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public function score($score, $user_id, $memo)
    {
        $user = self::get($user_id);
        if ($user && $score != 0) {
            $before = $user->score;
            $after = $user->score + $score;
            $level = self::nextlevel($after);
            //更新会员信息
            $user->save(['score' => $after, 'level' => $level]);
            //写入日志
            ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }

    /**
     * 处理地址信息
     */
    public function doarea(&$params){

        switch ($params['level']) {
            case '1':
                $params['zone_id'] = $params['province_id'];
                break;
            case '2':
                if(!isset($params['city_id'])){
                    $this->error('代理区域填写有误');
                }
                $params['zone_id'] = $params['city_id'];
                break;
            case '3':
                if(!isset($params['area_id'])){
                    $this->error('代理区域填写有误');
                }
                $params['zone_id'] = $params['area_id'];
                break;
            case '4':
                if(!isset($params['town_id'])){
                    $this->error('代理区域填写有误');
                }
                $params['zone_id'] = $params['town_id'];
                break;
            default:
                # code...
                break;
        }
        $area_name = db('cnarea2019')->field('merger_name')->where('area_code',$params['zone_id'])->find();
        $params['di_qu'] = $area_name['merger_name'];
        return $params;

    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params = $this->doarea($params);
            $red = $this->model->update($params);
            
            $this->token();
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[level]', 
        [1=>'共创合伙人',2=>'城市合伙人',3=>'区县合伙人',4=>'乡镇合伙人'], $row['level'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where('id',$row['id'])->delete();
        $this->success();
    }

    /**
     * 下拉测试
     */
    public function cxselect(){
        $parent_code = $this->request->get("area_code");
        $list = $this->areaModel
                ->field('area_code as value,name')
                ->where('parent_code',$parent_code)
                ->select();
        $list = collection($list)->toArray();
        $this->success('', null, $list);

    }

}
